package com.lmt.controller;

import com.lmt.entity.User;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Date;

/**
 * 用户Controller
 * Date 2018/06/27
 *
 * @author MT-Lin
 */
@RestController
public class UserController {

    private final RestTemplate restTemplate;

    private final LoadBalancerClient loadBalancerClient;

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    public UserController(RestTemplate restTemplate, LoadBalancerClient loadBalancerClient) {
        this.restTemplate = restTemplate;
        this.loadBalancerClient = loadBalancerClient;
    }
//   @HystrixCommand(fallbackMethod = "findByIdFallBack",
//           commandProperties = {
//           @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "5000"),
//                   @HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "10000")
//           },
//           threadPoolProperties = {
//           @HystrixProperty(name = "coreSize", value = "1"),
//                   @HystrixProperty(name = "maxQueueSize", value = "10")
//   })
    @HystrixCommand(fallbackMethod = "findUserByIdFallBack")
    @GetMapping("/findUserById")
    public User findUserById(@RequestParam(name = "id") String id){
        logger.warn("consumer-ribbon-hystrix->findUserById:id={}", id);
        String url = "http://provider/findUserById?id=" + id;
        return this.restTemplate.getForObject(url, User.class);
    }

    public User findUserByIdFallBack(String id){
        logger.warn("consumer-ribbon-hystrix->findUserByIdFallBack:id={}", id);
        User user = new User();
        user.setUserName("DefaultUserName");
        user.setGmtCreate(new Date());
        return user;
    }

    @RequestMapping("/logInstance")
    public void logInstance() {
        ServiceInstance serviceInstance = this.loadBalancerClient.choose("provider");
        this.logger.warn("\r\nconsumer-ribbon-hystrix->logInstance:\r\nServiceId:{}\r\nServiceHost:{}\r\nServicePort:{}\r\n",
                serviceInstance.getServiceId(),
                serviceInstance.getHost(),
                serviceInstance.getPort());
    }
}
